package org.example.videotran.utils;

import ch.qos.logback.classic.Logger;
import jakarta.servlet.ServletContext;
import org.apache.tika.Tika;
import org.example.videotran.exception.AppException;
import org.example.videotran.exception.AppExceptionCodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Component
public class FileUtils implements ServletContextAware {
    private static Logger logger;
    private ServletContext servletContext;

    @Value("${file.cleanup.maxAgeDays:7}")
    private static int maxAgeDays;

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public String uploadFile(MultipartFile file, String uploadPath) throws IOException {
        // 获取项目根目录（Tomcat 或 IDE 的根目录）
        String projectPath = System.getProperty("java.io.tmpdir");

        // 构建相对路径
        String uploadDir = projectPath + uploadPath;

        // 确保目标目录存在
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 上传文件
        File destFile = new File(uploadDir + file.getOriginalFilename());
        try {
            file.transferTo(destFile);  // 保存文件到相对路径指定的目录
        } catch (IOException e) {
            e.printStackTrace();
        }
        return destFile.getAbsolutePath();
    }

    public static String upload(MultipartFile file, String uploadPath) throws IOException {
        // 创建 FileUtils 类的实例
        FileUtils fileUtils = new FileUtils();

        // 通过实例调用非静态方法
        return fileUtils.uploadFile(file, uploadPath);  // 正常调用
    }

    public static boolean isSrtFileByContent(MultipartFile multipartFile) {
        Tika tika = new Tika();
        try (InputStream inputStream = multipartFile.getInputStream()) {
            String mimeType = tika.detect(inputStream, multipartFile.getOriginalFilename());
            System.out.println("mimeType" +mimeType);
            return "application/x-subrip".equals(mimeType);
        } catch (IOException e) {
            return false;
        }
    }

    public static void deleteFiles(String cleanupDirectory){
        File directory = new File(cleanupDirectory);

        if (!directory.exists() || !directory.isDirectory()) {
            logger.warn("清理目录不存在: {}", cleanupDirectory);
            throw new AppException(AppExceptionCodeMsg.NON_EXISTENT_DIRECTORY);
        }

        File[] files = directory.listFiles();
        if (files == null) return;

        long now = System.currentTimeMillis();
        long cutoff = now - (maxAgeDays * 24 * 60 * 60 * 1000L);

        for (File file : files) {
            if (file.isFile() && file.lastModified() < cutoff) {
                try {
                    boolean deleted = file.delete();
                    if (deleted) {
                        logger.info("已删除过期文件: {}", file.getAbsolutePath());
                    } else {
                        logger.error("删除文件失败: {}", file.getAbsolutePath());
                    }
                } catch (SecurityException e) {
                    logger.error("无权限删除文件: {}", file.getAbsolutePath(), e);
                }
            }
        }
    }

}
